package com.bruce.spring.http.client.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by bruce in 2023/12/6 02:13
 */
public class TraceFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(TraceFilter.class);

    private static final String TRACE_ID = "TraceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();
        long start = System.currentTimeMillis();
        try {
            chain.doFilter(request, response);
        } finally {
            long time = System.currentTimeMillis() - start;
            logger.info("请求结束,耗时:{}ms,Client ip:{},url:{}", time, request.getRemoteAddr() + ":" + request.getRemotePort(), requestURI);
        }

    }

}
